<template>
  <div class="export-project-container">
    <n-card class="export-card">
      <template #header>
        <div class="card-header">
          <h1>导出项目</h1>
          <div class="header-actions">
            <n-button @click="goBack">
              <template #icon><n-icon><ArrowBackOutline /></n-icon></template>
              返回
            </n-button>
          </div>
        </div>
      </template>
      
      <div class="content-layout">
        <div class="form-section">
          <n-form
            ref="formRef"
            :model="exportForm"
            :rules="formRules"
            label-placement="left"
            label-width="120"
            require-mark-placement="right-hanging"
          >
            <n-form-item label="导出格式" path="format">
              <n-select
                v-model:value="exportForm.format"
                :options="formatOptions"
                placeholder="请选择导出格式"
              />
            </n-form-item>
            
            <n-form-item label="质量" path="quality">
              <n-select
                v-model:value="exportForm.quality"
                :options="qualityOptions"
                placeholder="请选择质量"
              />
            </n-form-item>
            
            <n-form-item label="导出范围" path="range">
              <n-radio-group v-model:value="exportForm.rangeType">
                <n-space>
                  <n-radio value="full">整个项目</n-radio>
                  <n-radio value="custom">自定义范围</n-radio>
                </n-space>
              </n-radio-group>
              
              <div v-if="exportForm.rangeType === 'custom'" class="custom-range">
                <n-input-group>
                  <n-input-number
                    v-model:value="exportForm.range[0]"
                    placeholder="开始时间"
                    :min="0"
                    :max="projectDuration"
                    :step="1000"
                    :formatter="formatTime"
                  />
                  <n-text style="padding: 0 8px;">至</n-text>
                  <n-input-number
                    v-model:value="exportForm.range[1]"
                    placeholder="结束时间"
                    :min="exportForm.range[0] || 0"
                    :max="projectDuration"
                    :step="1000"
                    :formatter="formatTime"
                  />
                </n-input-group>
              </div>
            </n-form-item>
            
            <n-form-item label="文件名" path="filename">
              <n-input v-model:value="exportForm.filename" placeholder="请输入文件名" />
            </n-form-item>
            
            <n-form-item label="保存位置" path="directory">
              <n-input-group>
                <n-input
                  v-model:value="exportForm.directory"
                  placeholder="请选择保存位置"
                  readonly
                />
                <n-button @click="selectDirectory">
                  浏览...
                </n-button>
              </n-input-group>
            </n-form-item>
            
            <n-divider />
            
            <n-form-item label="高级选项">
              <n-space vertical>
                <n-checkbox v-model:checked="exportForm.includeAudio">
                  包含音频
                </n-checkbox>
                <n-checkbox v-model:checked="exportForm.optimizeForWeb" v-if="exportForm.format === 'mp4' || exportForm.format === 'webm'">
                  优化 Web 播放
                </n-checkbox>
                <n-checkbox v-model:checked="exportForm.includeMetadata">
                  包含元数据
                </n-checkbox>
                <n-checkbox v-model:checked="exportForm.createZip" v-if="exportForm.format === 'png-sequence' || exportForm.format === 'jpg-sequence'">
                  创建 ZIP 压缩包
                </n-checkbox>
              </n-space>
            </n-form-item>
            
            <n-form-item>
              <n-button type="primary" @click="startExport" :loading="exporting" :disabled="exporting">
                <template #icon><n-icon><CloudUploadOutline /></n-icon></template>
                开始导出
              </n-button>
            </n-form-item>
          </n-form>
        </div>
        
        <div class="preview-section">
          <div class="preview-header">
            <h3>预览</h3>
          </div>
          
          <div class="preview-container">
            <div class="preview-image">
              <img
                v-if="projectThumbnail"
                :src="projectThumbnail"
                alt="项目预览"
              />
              <n-empty v-else description="无可用预览" />
            </div>
            
            <div class="project-info">
              <div class="info-row">
                <span class="label">项目名称:</span>
                <span class="value">{{ projectName || '未命名项目' }}</span>
              </div>
              <div class="info-row">
                <span class="label">分辨率:</span>
                <span class="value">{{ projectResolution }}</span>
              </div>
              <div class="info-row">
                <span class="label">帧率:</span>
                <span class="value">{{ projectFrameRate }} FPS</span>
              </div>
              <div class="info-row">
                <span class="label">时长:</span>
                <span class="value">{{ formatDuration(projectDuration) }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <n-divider />
      
      <div class="export-progress" v-if="exporting">
        <h3>导出进度</h3>
        <n-progress
          type="line"
          :percentage="exportProgress"
          :processing="exportProgress < 100"
          :indicator-placement="'inside'"
          :height="24"
        />
        <div class="progress-info">
          <span>{{ exportStatus }}</span>
          <span>{{ formatTime(exportCurrentTime) }} / {{ formatTime(exportTotalTime) }}</span>
        </div>
      </div>
      
      <n-modal
        v-model:show="showExportSuccess"
        preset="dialog"
        title="导出成功"
        positive-text="打开文件位置"
        negative-text="关闭"
        @positive-click="openExportLocation"
        @negative-click="closeExportSuccess"
      >
        <n-space vertical>
          <p>项目已成功导出到:</p>
          <n-text code>{{ exportedFilePath }}</n-text>
        </n-space>
      </n-modal>
    </n-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useMessage } from 'naive-ui'
import {
  NCard,
  NButton,
  NIcon,
  NForm,
  NFormItem,
  NInput,
  NInputNumber,
  NInputGroup,
  NSelect,
  NRadioGroup,
  NRadio,
  NSpace,
  NCheckbox,
  NDivider,
  NProgress,
  NEmpty,
  NModal,
  NText,
  FormInst
} from 'naive-ui'
import {
  ArrowBackOutline,
  CloudUploadOutline
} from '@vicons/ionicons5'
import { useProjectStore } from '../../stores/projectStore'
import type { Project } from '../../types/project'
import { ElectronService } from '../../services/electron.service'
import { storeToRefs } from 'pinia'

const route = useRoute()
const router = useRouter()
const message = useMessage()
const projectStore = useProjectStore()
const { currentProject } = storeToRefs(projectStore)

// 表单引用
const formRef = ref<FormInst | null>(null)

// 获取项目ID
const projectId = computed(() => route.params.id as string)

// 项目信息
const projectName = ref('')
const projectThumbnail = ref('')
const projectDuration = ref(0)
const projectFrameRate = ref(30)
const projectResolution = ref('1280x720')

// 导出状态
const exporting = ref(false)
const exportProgress = ref(0)
const exportStatus = ref('准备中...')
const exportCurrentTime = ref(0)
const exportTotalTime = ref(0)
const showExportSuccess = ref(false)
const exportedFilePath = ref('')

// 导出表单数据
const exportForm = reactive({
  format: 'mp4',
  quality: 'high',
  rangeType: 'full',
  range: [0, 0] as [number, number],
  filename: '',
  directory: '',
  includeAudio: true,
  optimizeForWeb: true,
  includeMetadata: true,
  createZip: false
})

// 表单验证规则
const formRules = {
  filename: {
    required: true,
    message: '请输入文件名',
    trigger: 'blur'
  },
  directory: {
    required: true,
    message: '请选择保存位置',
    trigger: 'blur'
  }
}

// 格式选项
const formatOptions = [
  { label: 'MP4 视频', value: 'mp4' },
  { label: 'WebM 视频', value: 'webm' },
  { label: 'GIF 动画', value: 'gif' },
  { label: 'PNG 序列', value: 'png-sequence' },
  { label: 'JPG 序列', value: 'jpg-sequence' }
]

// 质量选项
const qualityOptions = [
  { label: '低 (更小的文件体积)', value: 'low' },
  { label: '中', value: 'medium' },
  { label: '高 (更好的质量)', value: 'high' }
]

// 格式化时间 (毫秒 -> MM:SS.ms)
const formatTime = (ms: number) => {
  const totalSeconds = Math.floor(ms / 1000)
  const minutes = Math.floor(totalSeconds / 60)
  const seconds = totalSeconds % 60
  const milliseconds = Math.floor((ms % 1000) / 10)
  
  return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}.${milliseconds.toString().padStart(2, '0')}`
}

// 格式化持续时间 (毫秒 -> MM:SS)
const formatDuration = (ms: number) => {
  const totalSeconds = Math.floor(ms / 1000)
  const minutes = Math.floor(totalSeconds / 60)
  const seconds = totalSeconds % 60
  
  return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
}

// 加载项目数据
const loadProject = async () => {
  try {
    const response = await projectStore.fetchProject(projectId.value)
    if (response && currentProject.value) {
      const project = currentProject.value
      projectName.value = project.name
      projectThumbnail.value = project.thumbnail || ''
      projectDuration.value = project.duration
      projectFrameRate.value = project.frameRate
      
      if (project.resolution) {
        projectResolution.value = `${project.resolution.width}x${project.resolution.height}`
      }
      
      // 设置导出表单默认值
      exportForm.filename = `${project.name || 'project'}_export`
      exportForm.range = [0, project.duration]
      exportTotalTime.value = project.duration
    } else {
      message.error('加载项目数据失败')
    }
  } catch (error) {
    console.error('加载项目数据错误:', error)
    message.error('加载项目数据时发生错误')
  }
}

// 选择保存目录
const selectDirectory = async () => {
  try {
    const result = await ElectronService.selectDirectory()
    if (result && result.path) {
      exportForm.directory = result.path
    }
  } catch (error) {
    console.error('选择目录错误:', error)
    message.error('选择保存位置时发生错误')
  }
}

// 开始导出
const startExport = async () => {
  try {
    await formRef.value?.validate()
    
    // 准备导出选项
    const exportOptions = {
      format: exportForm.format,
      quality: exportForm.quality,
      range: exportForm.rangeType === 'full' ? null : exportForm.range,
      filename: exportForm.filename,
      directory: exportForm.directory,
      includeAudio: exportForm.includeAudio,
      optimizeForWeb: exportForm.optimizeForWeb,
      includeMetadata: exportForm.includeMetadata,
      createZip: exportForm.createZip
    }
    
    // 开始导出
    exporting.value = true
    exportProgress.value = 0
    exportStatus.value = '准备中...'
    exportCurrentTime.value = 0
    
    // 设置进度监听
    ElectronService.onDownloadProgress((progress) => {
      exportProgress.value = Math.round(progress.percent)
      exportCurrentTime.value = Math.round((progress.percent / 100) * exportTotalTime.value)
      
      if (progress.percent < 10) {
        exportStatus.value = '准备导出素材...'
      } else if (progress.percent < 30) {
        exportStatus.value = '渲染帧...'
      } else if (progress.percent < 60) {
        exportStatus.value = '编码视频...'
      } else if (progress.percent < 80) {
        exportStatus.value = '处理音频...'
      } else if (progress.percent < 95) {
        exportStatus.value = '合成最终文件...'
      } else {
        exportStatus.value = '完成中...'
      }
    })
    
    // 调用导出API
    const response = await projectStore.exportProject({
      format: exportForm.format,
      quality: exportForm.quality,
      range: exportForm.rangeType === 'full' ? null : exportForm.range,
      filename: exportForm.filename,
      directory: exportForm.directory
    })
    
    // 处理导出结果
    if (response) {
      exportProgress.value = 100
      exportStatus.value = '导出完成'
      exportCurrentTime.value = exportTotalTime.value
      exportedFilePath.value = `${exportForm.directory}/${exportForm.filename}.${exportForm.format.split('-')[0]}`
      
      // 显示成功对话框
      showExportSuccess.value = true
    } else {
      message.error(projectStore.projectError || '导出失败')
      exporting.value = false
    }
  } catch (error) {
    console.error('导出错误:', error)
    message.error('导出时发生错误')
    exporting.value = false
  }
}

// 打开导出位置
const openExportLocation = () => {
  if (exportedFilePath.value) {
    ElectronService.showItemInFolder(exportedFilePath.value)
  }
  showExportSuccess.value = false
}

// 关闭导出成功对话框
const closeExportSuccess = () => {
  showExportSuccess.value = false
  exporting.value = false
  
  // 重置导出状态
  exportProgress.value = 0
  exportStatus.value = '准备中...'
  exportCurrentTime.value = 0
}

// 返回上一页
const goBack = () => {
  if (exporting.value) {
    message.warning('导出正在进行中，请等待完成')
    return
  }
  router.back()
}

// 初始化
onMounted(() => {
  loadProject()
})
</script>

<style lang="scss" scoped>
.export-project-container {
  padding: 20px;
  height: 100%;
  overflow-y: auto;
  
  .export-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      h1 {
        margin: 0;
        font-size: 24px;
        font-weight: 500;
      }
      
      .header-actions {
        display: flex;
        gap: 12px;
      }
    }
  }
  
  .content-layout {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 24px;
    margin-bottom: 20px;
    
    .form-section {
      padding-right: 12px;
      
      .custom-range {
        margin-top: 12px;
      }
    }
    
    .preview-section {
      .preview-header {
        margin-bottom: 16px;
        
        h3 {
          margin: 0;
        }
      }
      
      .preview-container {
        border: 1px solid var(--border-color);
        border-radius: 4px;
        overflow: hidden;
        
        .preview-image {
          height: 200px;
          display: flex;
          align-items: center;
          justify-content: center;
          background-color: #000;
          
          img {
            max-width: 100%;
            max-height: 100%;
            object-fit: contain;
          }
        }
        
        .project-info {
          padding: 12px;
          background-color: var(--card-color);
          
          .info-row {
            display: flex;
            margin-bottom: 6px;
            
            .label {
              width: 80px;
              color: var(--text-color-secondary);
            }
            
            .value {
              font-weight: 500;
            }
          }
        }
      }
    }
  }
  
  .export-progress {
    margin-top: 20px;
    
    h3 {
      margin-top: 0;
      margin-bottom: 12px;
    }
    
    .progress-info {
      display: flex;
      justify-content: space-between;
      margin-top: 8px;
      color: var(--text-color-secondary);
      font-size: 14px;
    }
  }
}

/* 响应式调整 */
@media (max-width: 768px) {
  .export-project-container {
    padding: 10px;
    
    .content-layout {
      grid-template-columns: 1fr;
      
      .preview-section {
        margin-top: 20px;
      }
    }
  }
}
</style> 